package com.itheima.servlet;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BasicServlet {
    //创建用户服务对象
    private UserService service = new UserServiceImpl();

    //测试类
    private void test(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet 中的 test() 方法被调用");
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置默认页码
        Integer pageNum = 1;
        String num = req.getParameter("pageNum");
        if (num != null) {
            pageNum = Integer.parseInt(num);
        }
        //获取用户列表
        List<User> userList = service.findAll(pageNum);
        //交给分页对象处理
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        //将数据存入requset域中
        req.setAttribute("pageInfo", pageInfo);
        //跳转
        req.getRequestDispatcher("/main.jsp").forward(req, resp);

    }

    //登录
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从请求域获取账号和密码
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        User user = service.login(email, password);
        //判断登录
        if (user != null) {
            req.getRequestDispatcher("/user/list").forward(req, resp);
        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }


}
